package com.janwen.j2ee.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ConnectionManager {

	private Connection connection = null;
	private ThreadLocal<Connection> thread_connection = new ThreadLocal<Connection>();
	static final Log logger = LogFactory.getLog(ConnectionManager.class);

	public Connection getConnection(String url, String username,
			String password, String driver) {
		try {
			if (thread_connection.get() == null) {
				Class.forName(driver);
				connection = DriverManager.getConnection(url, username,
						password);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return connection;
	}

	public void releasConnection() {

		try {
			if (thread_connection.get() != null
					&& !thread_connection.get().isClosed()) {
				connection.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
